<?php


namespace App\Services;


use App\Models\Pack;
use App\Models\PackVideo;
use App\Utils\Code;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class PackService extends BaseService
{
    /**
     * 创建数据
     * @param array $params
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     * @throws \Exception
     */
    public function store(array $params) {
        if (!$this->checkParams($params)){
            throw new \Exception('请求参数验证不通过', Code::PARAMETER_ERROR);
        }
        return DB::transaction(function () use ($params){
            $model = new Pack();
            if (Pack::where('name', $params['name'])->first()) {
                throw new \Exception('名称已经存在', Code::EXIST_REPEAT);
            }
            $model->name = $params['name'];
            if (isset($params['folder_id']) && is_numeric($params['folder_id'])){
                $model->folder_id = (int)$params['folder_id'];
            }
            return $model->save();
        });
    }
    
    // 新增视频
    public function addVideo(array $params) {
        if (!isset($params['video_ids']) || !is_array($params['video_ids'])) {
            throw new \Exception('视频ID不能为空', Code::PARAMETER_ERROR);
        }
        if (!isset($params['pack_id']) || !$params['pack_id']) {
            throw new \Exception('素材包ID不能为空', Code::PARAMETER_ERROR);
        }
        return DB::transaction(function () use ($params){
            if (!Pack::where('id', $params['pack_id'])->exists()) {
                throw new \Exception('素材包不存在', Code::EXIST_REPEAT);
            }
            foreach ($params['video_ids'] as $videoId) {
                if (!$model = PackVideo::where('video_id', $videoId)
                    ->where('id', $params['pack_id'])->first()) {
                    $model = new PackVideo();
                    $model->video_id = $videoId;
                    $model->pack_id = $params['pack_id'];
                    $model->save();
                }
            }
            return true;
        });
    }
    
    // 移除视频
    public function removeVideo(array $params) {
        if (!isset($params['video_ids']) || !is_array($params['video_ids'])) {
            throw new \Exception('视频ID不能为空', Code::PARAMETER_ERROR);
        }
        if (!isset($params['pack_id']) || !$params['pack_id']) {
            throw new \Exception('素材包ID不能为空', Code::PARAMETER_ERROR);
        }
        return DB::transaction(function () use ($params){
            if (!$model = Pack::where('id', $params['pack_id'])->first()) {
                throw new \Exception('素材包不存在', Code::EXIST_REPEAT);
            }
            return PackVideo::where('pack_id', $model->id)
                ->whereIn('video_id', $params['video_ids'])->delete();
        });
    }

    /**
     * 数据信息
     * @param $id
     * @param bool $simple
     * @param bool $abnormal
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     * @throws \Exception
     */
    public function show($id, $abnormal = true) {
        $model = Pack::where('id', $id)->first();
        if (!$model && $abnormal){
            throw new \Exception('不存在的ID', Code::EMPTY_DATA);
        }
        return $model;
    }

    /**
     * 更新数据
     * @param $id
     * @param array $params
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     * @throws \Exception
     */
    public function update($id, array $params) {
        if (!$this->checkParams($params, true)){
            throw new \Exception('请求参数验证不通过', Code::PARAMETER_ERROR);
        }
        return DB::transaction(function () use ($id, $params){
            $model = $this->show($id);
            if (Pack::where('name', $params['name'])->where('id', '<>', $id)->first()) {
                throw new \Exception('名称已经存在', Code::EXIST_REPEAT);
            }
            $model->name = $params['name'];
            if (isset($params['folder_id']) && is_numeric($params['folder_id'])){
                $model->folder_id = (int)$params['folder_id'];
            }
            $model->save();
            return $model;
        });
    }

    /**
     * 删除数据
     * @param $id
     * @return mixed
     * @throws \Exception
     */
    public function destroy(array $ids = []) {
        if (!$this::$admin) {
            throw new \Exception('你没有权限进行删除', Code::LACK_OF_CONDITIONS);
        }
        return DB::transaction(function () use ($ids) {
            return Pack::whereIn('id', $ids)->delete();
        });
    }

    /**
     * 数据分页
     * @param array $params
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function lists(array $params = []) {
        if (isset($params['mode']) && $params['mode'] == 'select') {
            $model = Pack::select(['id', 'name']);
        } else {
            $model = new Pack();
            $model = $model->with(['folder']);
        }
        if (isset($params['folder_id']) && $params['folder_id']) {
            $model = $model->where('folder_id', $params['folder_id']);
        }
        if (isset($params['name']) && $params['name']) {
            $model = $model->where('name', 'like', '%'.$params['name'].'%');
        }
        $lists = $model->orderBy('id', 'desc')->get();
        return $lists;
    }

    /**
     * 验证参数
     * @param array $params
     * @param bool $isUpdate
     * @return array
     * @throws \Exception
     */
    private function checkParams(array $params, $isUpdate = false){
        $rules = [
            'name' => ['bail', 'required', 'string', 'between:1,50'],
            'folder_id' => ['bail', 'nullable', 'integer'],
        ];
        if ($isUpdate){
            // 删除必选条件
            foreach ($rules as $field => &$rule){
                if (isset($rule[1]) && $rule[1] == 'required') {
                    unset($rule[1]);
                }
            }
        }
        $validator = Validator::make($params, $rules, [], [
            'name' => '名称',
            'folder_id' => '文件夹ID'
        ]);
        if ($validator->fails()) {
            throw new \Exception($validator->errors()->first(), Code::PARAMETER_ERROR);
        }
        return $params;
    }
}
